package com.testdemo.ui.activity.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.testdemo.R;
import com.testdemo.common.base.BaseActivity;
import com.testdemo.common.utils.ToastUtil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BluetoothConnectActivity extends BaseActivity {

    @Bind(R.id.tv)
    TextView tv;
    @Bind(R.id.et)
    EditText et;
    @Bind(R.id.btn_send)
    Button btnSend;



    //蓝牙串口服务
    public static final UUID SERIAL_PORT_SERVICE_CLASS_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    BluetoothDevice device;
    int type = 1;//1,作为服务器，2，作为客户端
    BluetoothServerSocket serverSocket;
    BluetoothSocket clientSocket;

    Thread connectThread;

    BufferedReader br;
    BufferedWriter bw;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            String string = (String) msg.obj;
            ToastUtil.showText(string);
        }
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_connect);
        ButterKnife.bind(this);

        device = getIntent().getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        type = getIntent().getIntExtra("type", 1);


        if (type == 1) {
            connectDeviceAsService(device, SERIAL_PORT_SERVICE_CLASS_UUID);
        } else {
            connectDeviceAsClient(device, SERIAL_PORT_SERVICE_CLASS_UUID);
        }

    }


    /**
     * 连接某个蓝牙设备（作为服务器）
     *
     * @param device
     */
    private void connectDeviceAsService(final BluetoothDevice device, final UUID uuid) {
        connectThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    serverSocket = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(device.getName() + "", uuid);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                BluetoothSocket bluetoothSocket = serverSocket.accept();
                                br = new BufferedReader(new InputStreamReader(bluetoothSocket.getInputStream()));
                                bw = new BufferedWriter(new OutputStreamWriter(bluetoothSocket.getOutputStream()));
                                while (true) {
                                    String string = null;
                                    if ((string = br.readLine()) != null) {
                                        Message msg = new Message();
                                        msg.what = 1;
                                        msg.obj = string;
                                        handler.sendMessage(msg);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                } catch (IOException e) {
                    Log.e("蓝牙连接：", device.getAddress() + "设备连接失败");
                    e.printStackTrace();
                }
            }
        });
        connectThread.start();
    }


    /**
     * 连接某个蓝牙设备（作为客户端）
     *
     * @param device
     */
    private void connectDeviceAsClient(final BluetoothDevice device, final UUID uuid) {
        connectThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    clientSocket = device.createRfcommSocketToServiceRecord(uuid);
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            try {
                                clientSocket.connect();
                                br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                                bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                                while (true) {
                                    String string = null;
                                    if ((string = br.readLine()) != null) {
                                        Message msg = new Message();
                                        msg.what = 2;
                                        msg.obj = string;
                                        handler.sendMessage(msg);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();


                } catch (IOException e) {
                    Log.e("蓝牙连接：", device.getAddress() + "设备连接失败");
                    e.printStackTrace();
                }
            }
        });
        connectThread.start();
    }

    @OnClick(R.id.btn_send)
    public void onViewClicked() {

        if (TextUtils.isEmpty(et.getText()) && bw!=null){
            try {
                bw.write(et.getText().toString());
                bw.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
